import datetime
import json
import time
from unicodedata import decimal

from wechatpayv3 import WeChatPay, WeChatPayType

from app.wxpay.config import MCHID, CERT_SERIAL_NO, APPID, APIV3_KEY, TIMEOUT, PRIVATE_KEY, NOTIFY_URL, CERT_DIR, \
    PARTNER_MODE, PROXY, LOGGER


class WxPay(object):

    def __init__(self):
        self.MCHID = MCHID
        self.CERT_SERIAL_NO = CERT_SERIAL_NO
        self.APPID = APPID
        self.APIV3_KEY = APIV3_KEY
        self.TIMEOUT = TIMEOUT
        self.PRIVATE_KEY = PRIVATE_KEY
        self.wxpay = WeChatPay(
            wechatpay_type=WeChatPayType.MINIPROG,
            mchid=MCHID,
            private_key=PRIVATE_KEY,
            cert_serial_no=CERT_SERIAL_NO,
            apiv3_key=APIV3_KEY,
            appid=APPID,
            notify_url=NOTIFY_URL,
            cert_dir=CERT_DIR,
            logger=LOGGER,
            partner_mode=PARTNER_MODE,
            proxy=PROXY,
            timeout=TIMEOUT
        )

    @staticmethod
    def unix_to_rfc3339(timestamp):
        dt = datetime.datetime.utcfromtimestamp(timestamp)
        # 格式化为 RFC 3339 格式
        rfc3339_format = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
        return rfc3339_format

    def place(self, payer, amount, description, out_trade_no):
        now = int(time.time())
        print(amount)
        try:
            code, message = self.wxpay.pay(
                description=description,
                out_trade_no=out_trade_no,
                payer=payer,
                time_expire=WxPay.unix_to_rfc3339(now + 1800),
                amount={'total': amount, 'currency': 'CNY'},
                pay_type=WeChatPayType.MINIPROG,
            )
            if code == 200:
                data = json.loads(message)
                return data['prepay_id']
        except Exception as e:
            print(e)
        # print(code, message)